<?php

namespace App\Store\Controllers\Financial\Business;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Common\Services\Store\Common as StoreCommon;

use App\Common\Services\CommonExcelExport;
use App\Store\Models\Account\Account;
use App\Store\Models\Account\SiteStore;
use App\Store\Models\Order\OrderRecoveryGoods;
use App\Store\Models\Order\OrderSalesGoods;
use App\Store\Models\Order\OrderSalesRecoveryGoods;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Maatwebsite\Excel\Facades\Excel;

/**
 * 销售业绩
 */
class SalesPerformanceController extends Controller
{

    public function getinfo(Request $request)
    {

        $store_id = intval($request->store_id);
        if ($store_id <= 0) {
            return response()->json(['code' => '001', 'msg' => '请选择门店']);
        }
        $info = StoreCommon::getCurrentAccountinfo($request);


        $query = Account::where(['cp_id' => $info['cp_id'], 'store_ids' => $store_id, 'is_del' => 1])->whereIn('type', [1, 2]);
        $store_ids = $info['store_ids'];
        if ($store_ids) {//权限控制
            if (is_array($store_ids)) {//获取当前权限下的门店
                $query->whereIn('store_ids', $store_ids);
            }
            if (is_numeric($store_ids) && intval($store_ids) > 0) {//获取当前门店下的列表
                $query->where('store_ids', intval($store_ids));
            }
        }
        $account_id = $request->account_id;
        if ($account_id > 0) {
            $query->where('id', $account_id);
        }

        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        if ($accountinfo['type'] == 11) {
            $training = StoreCommon::gettraining($request);
            if ($training['training_min'] == 0 && $training['training_max'] == 0) {
                return response()->json(['code' => '001', 'msg' => '培训账号，请先设置公司培训上下限']);
            }
        }

        $list = $query->get()->toArray();

        $where = [];
        $where[] = ['store_id', $store_id];
        $where[] = ['cp_id', $info['cp_id']];

        $where1 = [];
        $where1[] = ['store_id', $store_id];
        $where1[] = ['cp_id', $info['cp_id']];

        $goods_category_id = intval($request->goods_category_id);
        if ($goods_category_id > 0) {
            $where[] = ['goods_category_id', $goods_category_id];
            $where1[] = ['goods_category_id', $goods_category_id];
        }

        $is_sujin = intval($request->is_sujin) ?? 0;
//        if ($is_sujin > 0&& $is_sujin !=3) {
//            $where[] = ['is_sujin', $is_sujin];
//            $where1[] = ['is_sujin', $is_sujin];
//        }

        $order_at_start = strtotime($request->order_at_start);
        $order_at_end = strtotime($request->order_at_end);

        $classesset_id = intval($request->classesset_id);
        if ($classesset_id > 0) {
            $where[] = ['classesset_id', $classesset_id];
            $where1[] = ['classesset_id', $classesset_id];
        }

        $goods_brand_id = intval($request->goods_brand_id);
        if ($goods_brand_id > 0) {
            $where[] = ['goods_brand_id', $goods_brand_id];
        }

        $where[] = ['audit_status', 2];
        $where[] = ['performance', '<>', 0];


        $where1[] = ['audit_status', 2];
        $where1[] = ['performance', '<>', 0];


        $list_new = [];

        if ($accountinfo['type'] == 11) {
            $sales_where = $where + [
                    ['total_money', '>', $training['training_min']],
                    ['total_money', '<', $training['training_max']],
                ];
            $sales_recovery_where = $where1 + [
                    ['money', '>', $training['training_min']],
                    ['money', '<', $training['training_max']],
                ];
        } else {
            $sales_where = $where;
            $sales_recovery_where = $where1;
        }
        foreach ($list as &$val) {

            if ((int)$is_sujin > 0) {
                if ($is_sujin == 3) {
                    // 红冲
                    $redListsuArr = $this->getRedflush($val, $sales_where, $order_at_start, $order_at_end);
                } else {

                    if ($is_sujin == 1) {
                        $listsuArr = $this->getOrderPerformance($val, $sales_where, $sales_recovery_where, $order_at_start, $order_at_end, 1);
                    } else {
                        $listnotsuArr = $this->getOrderPerformance($val, $sales_where, $sales_recovery_where, $order_at_start, $order_at_end, 2);
                    }
                }
            } else {
                $listsuArr = $this->getOrderPerformance($val, $sales_where, $sales_recovery_where, $order_at_start, $order_at_end, 1);
                $listnotsuArr = $this->getOrderPerformance($val, $sales_where, $sales_recovery_where, $order_at_start, $order_at_end, 2);
                $redListsuArr = $this->getRedflush($val, $sales_where, $order_at_start, $order_at_end);
            }


            $val['su'] = $listsuArr ?? [];
            $val['notsu'] = $listnotsuArr ?? [];
            $val['red'] = $redListsuArr ?? [];

            // 为了排序造的值
            $val['total_performance'] = 0;

            if (!empty($listsuArr)) {
                $val['total_performance'] += array_sum(array_column($listsuArr, 'performance')) + array_sum(array_column($listsuArr, 'recover_performance'));
            }

            if (!empty($listnotsuArr)) {
                $val['total_performance'] += array_sum(array_column($listnotsuArr, 'performance')) + array_sum(array_column($listnotsuArr, 'recover_performance'));
            }
            if (!empty($redListsuArr)) {
                $val['total_performance'] += array_sum(array_column($redListsuArr, 'performance'));
            }

            $list_new[] = $val;
        }


        $listsort = array_column($list_new, 'total_performance');
        $sort = intval($request->sort);
        if ($sort == 1) {
            array_multisort($listsort, SORT_ASC, $list_new);
        } elseif ($sort == 2) {
            array_multisort($listsort, SORT_DESC, $list_new);
        }


        if ($request->isdoexport == 1) {
            return $this->doexexport($list_new, $store_id);
        } else {
            foreach ($list_new as $k => &$v) {

                foreach ($v['su'] as $sk => &$sval) {
                    $sval['account_id'] = $v['id'];
                    $sval['is_sujin'] = 1;
                    $sval['real_name'] = $v['real_name'];
                    $sval['type'] = '素金';
                    if ($sval['total_performance'] <= 0) {
                        unset($v['su'][$sk]);
                    }
                }

                $suGroup = [];
                foreach ($v['su'] as $su) {
                    $suGroup[$su['goods_category_id']][] = $su;
                }


                $suArr = [];
                foreach ($suGroup as $sug) {
                    $suArr[] = [
                        'performance' => array_sum(array_column($sug, 'performance')),
                        'count' => array_sum(array_column($sug, 'count')),
                        'weight' => round(array_sum(array_column($sug, 'weight')), 3),
                        'total_money' => array_sum(array_column($sug, 'total_money')),
                        'real_total_money' => array_sum(array_column($sug, 'real_total_money')),
                        'recover_performance' => array_sum(array_column($sug, 'recover_performance')),
                        'goods_category_id' => $sug[0]['goods_category_id'],
                        'goods_category' => $sug[0]['goods_category'],
                        'account_id' => $v['id']??0,
                        'is_sujin' => $sug[0]['is_sujin'],
                        'real_name' => $sug[0]['real_name'],
                        'type' => $sug[0]['type'],
                        'total_performance' => array_sum(array_column($sug, 'total_performance')),
                    ];

                }

                $v['su'] = array_values($suArr);

                foreach ($v['notsu'] as $nsk => &$nsval) {
                    $nsval['account_id'] = $v['id'];
                    $nsval['is_sujin'] = 2;
                    $nsval['real_name'] = $v['real_name'];
                    $nsval['type'] = '非素';
                    if ($nsval['total_performance'] <= 0) {
                        unset($v['notsu'][$nsk]);
                    }
                }

                $notsuGroup = [];
                foreach ($v['notsu'] as $su) {
                    $notsuGroup[$su['goods_category_id']][] = $su;
                }

                $notsuArr = [];
                foreach ($notsuGroup as $notsug) {
                    $notsuArr[] = [
                        'performance' => array_sum(array_column($notsug, 'performance')),
                        'count' => array_sum(array_column($notsug, 'count')),
                        'weight' => round(array_sum(array_column($notsug, 'weight')), 3),
                        'total_money' => array_sum(array_column($notsug, 'total_money')),
                        'real_total_money' => array_sum(array_column($notsug, 'real_total_money')),
                        'recover_performance' => array_sum(array_column($notsug, 'recover_performance')),
                        'goods_category_id' => $notsug[0]['goods_category_id'],
                        'goods_category' => $notsug[0]['goods_category'],
                        'account_id' => $v['id']??0,
                        'is_sujin' => $notsug[0]['is_sujin'],
                        'real_name' => $notsug[0]['real_name'],
                        'type' => $notsug[0]['type'],
                        'total_performance' => array_sum(array_column($notsug, 'total_performance')),
                    ];

                }
                $v['notsu'] = array_values($notsuArr);


                $redArr = [];
                $redGroup = [];
                foreach ($v['red'] as &$rd) {
                    $rd['type'] = '红冲';
                    $rd['real_name'] = $v['real_name'];
                    $redGroup[$rd['goods_category_id']][] = $rd;
                }


                foreach ($redGroup as $re) {
                    $redArr[] = [
                        'performance' => array_sum(array_column($re, 'performance')),
                        'count' => array_sum(array_column($re, 'count')),
                        'weight' => round(array_sum(array_column($re, 'weight')), 3),
                        'total_money' => array_sum(array_column($re, 'total_money')),
                        'real_total_money' => array_sum(array_column($re, 'real_total_money')),
                        'recover_performance' => array_sum(array_column($re, 'recover_performance')),
                        'goods_category_id' => $re[0]['goods_category_id'] ?? '',
                        'goods_category' => $re[0]['goods_category'] ?? '',
                        'account_id' => $v['id']??0,
                        'is_sujin' => $re[0]['is_sujin'] ?? 0,
                        'real_name' => $re[0]['real_name'] ?? '',
                        'type' => $re[0]['type'],
                        'total_performance' => array_sum(array_column($re, 'total_performance')),
                    ];

                }

                $v['red'] = array_values($redArr);

                $v['total'][] = [
                    'account_id' => $v['id'],
                    'is_sujin' => '',
                    'real_name' => $v['real_name'],
                    'type' => '小计',
                    'count' => array_sum(array_column($v['su'], 'count')) + array_sum(array_column($v['notsu'], 'count')) + array_sum(array_column($v['red'], 'count')),
                    'weight' => round(array_sum(array_column($v['su'], 'weight')) + array_sum(array_column($v['notsu'], 'weight')) + array_sum(array_column($v['red'], 'weight')), 3),
                    'total_money' => (array_sum(array_column($v['su'], 'total_money')) + array_sum(array_column($v['notsu'], 'total_money'))) + array_sum(array_column($v['red'], 'total_money')),
                    'real_total_money' => (array_sum(array_column($v['su'], 'real_total_money')) + array_sum(array_column($v['notsu'], 'real_total_money'))) + array_sum(array_column($v['red'], 'real_total_money')),
                    'recover_performance' => (array_sum(array_column($v['su'], 'recover_performance')) + array_sum(array_column($v['notsu'], 'recover_performance'))) + array_sum(array_column($v['red'], 'recover_performance')),
                    'total_performance' => (array_sum(array_column($v['su'], 'total_performance')) + array_sum(array_column($v['notsu'], 'total_performance')) + array_sum(array_column($v['red'], 'total_performance')))
                ];

//                $total_performance = array_sum(array_column($v['total'], 'total_performance'));
//                if ($total_performance <= 0) {
//                    unset($list_new[$k]);
//                }
            }

        }


        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => ['list' => array_values($list_new)]]);
    }


    protected function doexexport($list_new, $store_id)
    {
        $exceldata = [];
        $keynum = 1;

        $store_name = SiteStore::where(['id' => $store_id])->value('store_name');
        $row = [
            ['keynum' => '销售业绩表'],
            ['keynum' => '所属门店：' . $store_name],
            [
                'keynum' => '序号',
                'real_name' => '导购员',
                'performance_type' => '业绩类型',
                'category_name' => '类别',
                'count' => '件数',
                'weight' => '金重（G）',
                'total_money' => '销售金额（元）',
                'real_total_money' => '实收金额（元）',
                'recover_performance' => '回收业绩',
                'total_performance' => '业绩合计',
            ]];

        $initcont = count($row) + 1;
        $mergecell = [];
        foreach ($list_new as &$v) {
            foreach ($v['notsu'] as &$sval) {
                $sval['category_name'] = $sval['goods_category']['category_name'];
                $sval['total_performance'] = $sval['performance'] + $sval['recover_performance'];


            }


            $notsuGroup = [];
            foreach ($v['notsu'] as $notsu) {
                $total_performance = ($notsu['performance'] + $notsu['recover_performance']) / 100;
                if ($total_performance > 0) {
                    $notsuGroup[$notsu['goods_category_id']][] = $notsu;
                }

            }


            $notsuArr = [];
            foreach ($notsuGroup as $notsug) {
                $notsuArr[] = [
                    'keynum' => $keynum,
                    'real_name' => $v['real_name'],
                    'performance_type' => '非素',
                    'category_name' => $notsug[0]['category_name'],
                    'count' => array_sum(array_column($notsug, 'count')),
                    'weight' => round(array_sum(array_column($notsug, 'weight')), 3),
                    'total_money' => array_sum(array_column($notsug, 'total_money')) / 100,
                    'real_total_money' => array_sum(array_column($notsug, 'real_total_money')) / 100,
                    'recover_performance' => array_sum(array_column($notsug, 'recover_performance')) / 100,
                    'total_performance' => (array_sum(array_column($notsug, 'performance')) + array_sum(array_column($notsug, 'recover_performance'))) / 100,
                ];
            }

            $v['notsu'] = array_values($notsuArr);

            foreach ($v['su'] as &$val) {
                $val['category_name'] = $val['goods_category']['category_name'];
                $val['total_performance'] = $val['performance'] + $val['recover_performance'];
            }


            $suGroup = [];
            foreach ($v['su'] as $su) {
                $suGroup[$su['goods_category_id']][] = $su;
            }

            $suArr = [];
            foreach ($suGroup as $sug) {
                $suArr[] = [
                    'keynum' => $keynum,
                    'real_name' => $v['real_name'],
                    'performance_type' => '素金',
                    'category_name' => $sug[0]['category_name'],
                    'count' => array_sum(array_column($sug, 'count')),
                    'weight' => round(array_sum(array_column($sug, 'weight')), 3),
                    'total_money' => array_sum(array_column($sug, 'total_money')) / 100,
                    'real_total_money' => array_sum(array_column($sug, 'real_total_money')) / 100,
                    'recover_performance' => array_sum(array_column($sug, 'recover_performance')) / 100,
                    'total_performance' => (array_sum(array_column($sug, 'performance')) + array_sum(array_column($sug, 'recover_performance'))) / 100,
                ];
            }

            $v['su'] = array_values($suArr);

            foreach ($v['red'] as &$red) {
                $red['category_name'] = $red['goods_category']['category_name'];
            }

            $redGroup = [];
            foreach ($v['red'] as $rd) {
                $redGroup[$rd['goods_category_id']][] = $rd;
            }

            $redArr = [];
            foreach ($redGroup as $re) {
                $redArr[] = [
                    'keynum' => $keynum,
                    'real_name' => $v['real_name'],
                    'performance_type' => '红冲',
                    'category_name' => $re[0]['category_name'],
                    'count' => array_sum(array_column($re, 'count')),
                    'weight' => round(array_sum(array_column($re, 'weight')), 3),
                    'total_money' => array_sum(array_column($re, 'total_money')) / 100,
                    'real_total_money' => array_sum(array_column($re, 'real_total_money')) / 100,
                    'recover_performance' => array_sum(array_column($re, 'recover_performance')) / 100,
                    'total_performance' => array_sum(array_column($re, 'total_performance')) / 100,
                ];
            }
            $v['red'] = array_values($redArr);

            $mergecell[] = 'A' . $initcont . ':A' . $initcont + count($v['su']) + count($v['notsu']) + count($v['red']);
            $mergecell[] = 'B' . $initcont . ':B' . $initcont + count($v['su']) + count($v['notsu']) + count($v['red']);

            if (!empty($v['notsu'])) {
                $mergecell[] = 'C' . $initcont . ':C' . $initcont + count($v['notsu']) - 1;
                $initcont = $initcont + count($v['notsu']);
            }

            if (!empty($v['su'])) {
                $mergecell[] = 'C' . $initcont . ':C' . $initcont + count($v['su']) - 1;
                $initcont = $initcont + count($v['su']);
            }

            if (!empty($v['red'])) {
                $mergecell[] = 'C' . $initcont . ':C' . $initcont + count($v['red']) - 1;
                $initcont = $initcont + count($v['red']);
            }

            $initcont = $initcont + 1;//小计

            $real_total_money = array_sum(array_column($v['su'], 'real_total_money')) + array_sum(array_column($v['notsu'], 'real_total_money')) + array_sum(array_column($v['red'], 'real_total_money'));
            $exceldata = array_merge($exceldata, $notsuArr, $suArr, $redArr);


            if ($real_total_money > 0) {
                $exceldata[] = [
                    'keynum' => $keynum,
                    'real_name' => $v['real_name'],
                    'performance_type' => '小计',
                    'category_name' => '',
                    'count' => array_sum(array_column($v['su'], 'count')) + array_sum(array_column($v['notsu'], 'count')) + array_sum(array_column($v['red'], 'count')),
                    'weight' => array_sum(array_column($v['su'], 'weight')) + array_sum(array_column($v['notsu'], 'weight')) + array_sum(array_column($v['red'], 'weight')),
                    'total_money' => (array_sum(array_column($v['su'], 'total_money')) + array_sum(array_column($v['notsu'], 'total_money')) + array_sum(array_column($v['red'], 'total_money'))),
                    'real_total_money' => (array_sum(array_column($v['su'], 'real_total_money')) + array_sum(array_column($v['notsu'], 'real_total_money')) + array_sum(array_column($v['red'], 'real_total_money'))),
                    'recover_performance' => (array_sum(array_column($v['su'], 'recover_performance')) + array_sum(array_column($v['notsu'], 'recover_performance')) + array_sum(array_column($v['red'], 'recover_performance'))),
                    'total_performance' => (array_sum(array_column($v['su'], 'total_performance')) + array_sum(array_column($v['notsu'], 'total_performance')) + array_sum(array_column($v['red'], 'total_performance')))
                ];
            }


            $keynum++;
        }

        $filename = '销售业绩表导出_' . time() . '.xlsx';
        return Excel::download(new CommonExcelExport($row, $exceldata, [], $mergecell), $filename);

    }


    public function getinfobycount(Request $request)
    {
        $store_id = intval($request->store_id);
        if ($store_id <= 0) {
            return response()->json(['code' => '001', 'msg' => '请选择门店']);
        }
        $info = StoreCommon::getCurrentAccountinfo($request);
        $account_id = $request->account_id ?? 0;

        $where = [];
        $where[] = ['store_id', $store_id];
        $where[] = ['cp_id', $info['cp_id']];
        $where1 = [];
        $where1[] = ['store_id', $store_id];
        $where1[] = ['cp_id', $info['cp_id']];

        $goods_category_id = intval($request->goods_category_id);
        if ($goods_category_id > 0) {
            $where[] = ['goods_category_id', $goods_category_id];
            $where1[] = ['goods_category_id', $goods_category_id];
        }

        $is_sujin = intval($request->is_sujin);
        if ($is_sujin > 0) {
            $where[] = ['is_sujin', $is_sujin];
            $where1[] = ['is_sujin', $is_sujin];
        }
        $is_red = $request->is_red??0;
        $order_at_start = strtotime($request->order_at_start);
        $order_at_end = strtotime($request->order_at_end);
        if ($order_at_start > 0 && $order_at_end > $order_at_start) {
            if($is_red>0){
                $where[] = ['red_audit_at', '>=', $order_at_start];
                $where[] = ['red_audit_at', '<=', $order_at_end];
            }else{
                $where[] = ['audit_at', '>=', $order_at_start];
                $where[] = ['audit_at', '<=', $order_at_end];

                $where1[] = ['audit_at', '>=', $order_at_start];
                $where1[] = ['audit_at', '<=', $order_at_end];
            }

        }

        $classesset_id = intval($request->classesset_id);
        if ($classesset_id > 0) {
            $where[] = ['classesset_id', $classesset_id];
            $where1[] = ['classesset_id', $classesset_id];
        }

        $goods_brand_id = intval($request->goods_brand_id);
        if ($goods_brand_id > 0) {
            $where[] = ['goods_brand_id', $goods_brand_id];
        }



        if ($is_red > 0) {
            $where[] = ['audit_status', 2];
            $where[] = ['performance', '<>',0];
            $where[] = ['red_audit_status', 2];
            $where[] = ['red_status', 2];
        }else{
            $where[] = ['performance', '<>',0];
            $where[] = ['audit_status', 2];
            $where[] = ['red_status', 1];
            $where1[] = ['performance', '<>',0];
            $where1[] = ['audit_status', 2];
        }







        $ordergoodslist = OrderSalesGoods::with(['memberinfo', 'storeinfo', 'orderinfo', 'shoppingaccountinfo1'])
            ->where($where)
            ->when($account_id>0,function ($q) use ($account_id){
                $q->where(function ($q) use ($account_id){
                    $q->where('shopping_account_id1', $account_id)
                        ->orWhere('shopping_account_id2', $account_id);
                });
            })
            ->get()
            ->toArray();
        if($is_red>0){
            $orderrecoverygoods =[];
        }else{
            $orderrecoverygoods = OrderSalesRecoveryGoods::with(['memberinfo', 'storeinfo', 'orderinfo', 'shoppingaccountinfo1', 'goods_category'])
                ->where($where1)
                ->when($account_id>0,function ($q) use ($account_id){
                    $q->where(function ($q) use ($account_id){
                        $q->where('shopping_account_id1', $account_id)
                            ->orWhere('shopping_account_id2', $account_id);
                    });

                })
                ->get()
                ->toArray();
        }


        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => ['ordergoodslist' => $ordergoodslist, 'orderrecoverygoods' => $orderrecoverygoods]]);


    }


    public function getOrderPerformance($val, $sales_where, $sales_recovery_where, $order_at_start, $order_at_end, $is_sujin = 1)
    {
        // 开单包含红冲业绩
        $list_1 = OrderSalesGoods::with(['goods_category'])->where($sales_where)
            ->where('is_sujin', $is_sujin)->where(function ($q) use ($val) {
                $q->where('shopping_account_id1', $val['id'])->orWhere('shopping_account_id2', $val['id']);
            })->where(function ($q) use ($order_at_start, $order_at_end) {
                if ($order_at_start > 0 && $order_at_end > $order_at_start) {
                    $q->where([['order_at', '>=', $order_at_start], ['order_at', '<=', $order_at_end]]);
                    //->orWhere([['red_audit_at','>=',$order_at_start],['red_audit_at','<=',$order_at_end]]);
                }

            })
            ->groupBy('goods_category_id')
            ->select([
                DB::raw('IFNULL(sum(performance),0) as performance'),
                DB::raw('IFNULL(sum(count),0) as count'),
                DB::raw('IFNULL(sum(weight),0) as weight'),
                DB::raw('IFNULL(sum(total_money),0) as total_money'),
                DB::raw('sum(real_total_money) as real_total_money'),
                DB::raw('"0" as recover_performance'), 'goods_category_id',
                //  DB::raw('IFNULL(sum(if(red_audit_status = 2,performance,0)),0) as redperformance')
            ])
//                ->select([
//                    DB::raw('IFNULL(sum(performance),0) as performance'), DB::raw('IFNULL(sum(if(red_status = 1,count,0)),0) as count'),
//                    DB::raw('IFNULL(sum(if(red_status = 1,weight,0)),0) as weight'), DB::raw('IFNULL(sum(if(red_status = 1,total_money,0)),0) as total_money'),
//                    DB::raw('IFNULL(sum(if(red_status = 1,real_total_money,0)),0) as real_total_money'), DB::raw('"0" as recover_performance'), 'goods_category_id',
//                    DB::raw('IFNULL(sum(if(red_audit_status = 2,performance,0)),0) as redperformance')
//                ])
            ->get()
            ->toArray();
        // 开单回收的
        $list_2 = OrderSalesRecoveryGoods::with(['goods_category'])
            ->where($sales_recovery_where)
            ->where('is_sujin', $is_sujin)
            ->where(function ($q) use ($val) {
                $q->where('shopping_account_id1', $val['id'])
                    ->orWhere('shopping_account_id2', $val['id']);
            })->where(function ($q) use ($order_at_start, $order_at_end) {
                if ($order_at_start > 0 && $order_at_end > $order_at_start) {
                    $q->where([['order_at', '>=', $order_at_start], ['order_at', '<=', $order_at_end]]);
                }

            })
            ->groupBy('goods_category_id')
            ->select([
                DB::raw('"0" as performance'),
                DB::raw('count'),
                DB::raw('weight'),
                DB::raw('"0" as total_money'),
                DB::raw('"0" as real_total_money'),
                DB::raw('IFNULL(sum(performance),0) as recover_performance'), 'goods_category_id',
                // DB::raw('"0" as redperformance'),
            ])
            ->get()
            ->toArray();


        // 纯回收的
        $list_3 = OrderRecoveryGoods::with(['goods_category'])
            ->where($sales_recovery_where)
            ->where('is_sujin', $is_sujin)
            ->where(function ($q) use ($val) {
                $q->where('shopping_account_id1', $val['id'])
                    ->orWhere('shopping_account_id2', $val['id']);
            })->where(function ($q) use ($order_at_start, $order_at_end) {
                if ($order_at_start > 0 && $order_at_end > $order_at_start) {
                    $q->where([['order_at', '>=', $order_at_start], ['order_at', '<=', $order_at_end]]);
                }

            })
            ->groupBy('goods_category_id')
            ->select([
                DB::raw('"0" as performance'),
                DB::raw('"0" as count'),
                DB::raw('"0" as weight'),
                DB::raw('"0" as total_money'),
                DB::raw('"0" as real_total_money'),
                DB::raw('IFNULL(sum(performance),0) as recover_performance'),
                'goods_category_id',
                // DB::raw('"0" as redperformance'),
            ])
            ->get()
            ->toArray();

        if ($list_1 && $list_2) {
            foreach ($list_2 as $suval) {
                $f = array_filter($list_1, function ($item) use ($suval) {
                    $item['goods_category_id'] == $suval['goods_category_id'];
                });
                if ($f) {
                    foreach ($f as $fk => $fval) {
                        $list_1[$fk]['recover_performance'] += $suval['recover_performance'];
                        break;
                    }
                } else {
                    $list_1[] = $suval;
                }
            }
        } else {
            if ($list_1 || $list_2) {
                $list_1 = $list_1 ? $list_1 : $list_2;
            } else {
                $list_1 = [];
            }
        }


        if ($list_1 && $list_3) {
            foreach ($list_3 as $suval) {
                $f = array_filter($list_1, function ($item) use ($suval) {
                    $item['goods_category_id'] == $suval['goods_category_id'];
                });
                if ($f) {
                    foreach ($f as $fk => $fval) {
                        $list_1[$fk]['recover_performance'] += $suval['recover_performance'];
                        break;
                    }
                } else {
                    $list_1[] = $suval;
                }
            }
        } else {
            if ($list_1 || $list_3) {
                $list_1 = $list_1 ? $list_1 : $list_3;
            } else {
                $list_1 = [];
            }
        }

        foreach ($list_1 as &$item) {
            $item['total_performance'] = $item['real_total_money'] + $item['recover_performance'];
        }

        return $list_1;
    }

    /**
     *  红冲的订单
     * @param $val
     * @param $sales_where
     * @param $order_at_start
     * @param $order_at_end
     * @param $is_sujin
     * @return mixed[]
     */
    public function getRedflush($val, $sales_where, $order_at_start, $order_at_end)
    {
        $list = OrderSalesGoods::with(['goods_category'])
            ->where($sales_where)
            ->where('red_status', 2)
            ->where('red_audit_status', 2)
            ->where(function ($q) use ($val) {
                $q->where('shopping_account_id1', $val['id'])->orWhere('shopping_account_id2', $val['id']);
            })->where(function ($q) use ($order_at_start, $order_at_end) {
                if ($order_at_start > 0 && $order_at_end > $order_at_start) {
                    $q->where([['red_audit_at', '>=', $order_at_start], ['red_audit_at', '<=', $order_at_end]]);
                }

            })
            ->groupBy('goods_category_id')
            ->select([
                DB::raw('IFNULL(sum(performance),0) as performance'),
                DB::raw('IFNULL(sum(count),0) as count'),
                DB::raw('IFNULL(sum(weight),0) as weight'),
                DB::raw('IFNULL(sum(total_money),0) as total_money'),
                DB::raw('sum(real_total_money) as real_total_money'),
                DB::raw('"0" as recover_performance'), 'goods_category_id',
            ])
            ->get()
            ->toArray();

        foreach ($list as &$item) {
            $item['performance'] = $item['performance'] > 0 ? -$item['performance'] : 0;
            $item['count'] = $item['count'] > 0 ? -$item['count'] : 0;
            $item['weight'] = $item['weight'] > 0 ? -$item['weight'] : 0;
            $item['total_money'] = $item['total_money'] > 0 ? -$item['total_money'] : 0;
            $item['real_total_money'] = $item['real_total_money'] > 0 ? -$item['real_total_money'] : 0;
            $item['recover_performance'] = $item['recover_performance'] > 0 ? -$item['recover_performance'] : 0;
            $item['total_performance'] = $item['performance'] + $item['recover_performance'];

        }

        return $list;
    }

}
